<?php


namespace App\Admin\Actions\Tools;


use App\Admin\Actions\BatchAction;
use App\Models\AdminUser;
use App\PatentApply;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\Request;

class PatentApplyFundingBatchAction extends BatchAction
{
    protected $selector = '.funding-posts';

    public function handle(Collection $collection, Request $request)
    {
        $ratio = $request->get('ratio');
        $funding = $request->get('funding');
        $remark = $request->get('remark');
        if ($ratio && $funding) {
            $this->response()->status = false;
            return $this->response()->swal()->error('只能选择一种方式');
        }
        if (!is_numeric($ratio) && !is_numeric($funding)) {
            $this->response()->status = false;
            return $this->response()->swal()->error('请选择一种方式');
        }
        if ($ratio) {
            if (!is_numeric($ratio) || $ratio < 0) {
                $this->response()->status = false;
                return $this->response()->swal()->error('方式1请填写有效数字');
            }
            $funding = 0;
        } elseif ($funding) {
            if (!is_numeric($funding) || $funding < 0) {
                $this->response()->status = false;
                return $this->response()->swal()->error('请填写有效金额！');
            }
            $ratio = 0;
        }
        foreach ($collection as $model) {
            if ($model instanceof PatentApply) {
                if ($ratio > 0) {
                    $model->funding = round($ratio * $model['score'] / 100);
                } else {
                    $model->funding = $funding;
                }
                $model->funding_remark = $remark;
                $model->save();
            }
        }
        return $this->response()->success('操作成功！')->refresh();
    }

    public function form()
    {
        $this->text('ratio', '方式1：资助经费基数')->help('资助经费金额 = 资助经费基数*综合评分/100');
        $this->text('funding', '方式2：资助经费金额(元)');
        $this->textarea('remark', '备注');
    }

    public function html()
    {
        return "<a class='funding-posts btn btn-sm btn-primary'>资助经费</a>";
    }

    public function authorize(AdminUser $user, Collection $collection)
    {
        return $user->role_type == 1;
    }

    public function render()
    {
        if (!config('settings.patent_s_ratio_show')) {
            return '';
        }
        return parent::render();
    }

}
